package com.msc.cili.web.viewcontroller.guestmessagecontroller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.msc.cili.common.api.Result;
import com.msc.cili.common.utils.BdUtil;
import com.msc.cili.infrastructure.mail.MailService;
import com.msc.cili.repository.entity.guestmessage.Comment;
import com.msc.cili.service.guestmessage.CommentService;
import com.msc.cili.service.guestmessage.bo.PageCommentBo;
import com.msc.cili.web.annotation.AccessLimit;
import com.msc.cili.web.annotation.VisitLogger;
import com.msc.cili.web.viewcontroller.guestmessagecontroller.vo.PageCommentVo;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 评论前端控制器
 *
 * @author coder-msc
 * @date 2021-04-08
 */
@RestController
public class CommentViewController {
    Logger logger = LoggerFactory.getLogger(CommentViewController.class);

    @Autowired
    CommentService commentService;
    @Autowired
    MailService mailService;

    /**
     * 分页查询所有评论
     */
//    @RequiresAuthentication
//    @RequiresPermissions("user:read")
//    @GetMapping("/commentList")
//    public Result getCommentListByPage(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer pageSize) {
//
//
//        Page page = new Page(currentPage, pageSize);
//        IPage pageData = commentService.page(page, new QueryWrapper<Comment>().orderByDesc("create_time"));
//
//        //Assert.notNull(blog, "该博客已删除！");
//        return Result.succ(pageData);
//
//    }


    /**
     * 分页查询某个博客下的根评论
     */
//    @RequiresAuthentication
//    @RequiresPermissions("user:read")
//    @GetMapping("/comment/detail")
//    public Result getCommentListByPageId(@RequestParam(defaultValue = "1") Long blogId, @RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer pageSize) {
//
//        Page page = new Page(currentPage, pageSize);
//        IPage pageData = commentService.page(page, new QueryWrapper<Comment>().eq("blog_id", blogId).orderByDesc("create_time"));
//
//        //Assert.notNull(blog, "该博客已删除！");
//        return Result.succ(pageData);
//
//    }


    /**
     * 获取某个博客下的所有评论
     */
    @GetMapping("/comment/{blogId}")
    public Result getCommentByBlogId(@PathVariable(name = "blogId") Long blogId) {

        //实体模型集合对象转换为VO对象集合
        List<PageCommentBo> pageCommentListByDesc = commentService.getPageCommentListByDesc(blogId, (long) -1);
        List<PageCommentVo> pageComments = BdUtil.bo2do4List(pageCommentListByDesc, PageCommentVo.class);
//        List<PageComment> pageComments = commentService.getPageCommentListByDesc(blogId, (long) -1);

        for (PageCommentVo pageComment : pageComments) {

            List<PageCommentBo> replyBo = commentService.getPageCommentList(blogId, pageComment.getId());
            pageComment.setReplyComments(BdUtil.bo2do4List(replyBo, PageCommentVo.class));
        }
        //Assert.notNull(blog, "该博客已删除！");
        return Result.succ(pageComments);

    }

    /**
     * 修改评论的状态
     */
//    @RequiresAuthentication
//    @RequiresPermissions("user:update")
//    @RequestMapping("comment/publish/{id}")
//    public Result publish(@PathVariable(name = "id") String id) {
//        Comment comment = commentService.getById(id);
//        comment.setIsPublished(!comment.getIsPublished());
////        Friend temp = new Friend();
////        BeanUtil.copyProperties(friend, temp);
//        commentService.saveOrUpdate(comment);
//        return Result.succ(null);
//
//    }

    /**
     * 修改评论
     */
//    @RequiresAuthentication
//    @RequiresPermissions("user:update")
//    @RequestMapping("comment/update")
//    public Result updateById(@Validated @RequestBody Comment comment) {
//        if (comment == null) {
//            return Result.fail("不能为空");
//        }
////        Friend temp = new Friend();
////        BeanUtil.copyProperties(friend, temp);
//        commentService.saveOrUpdate(comment);
//        return Result.succ(null);
//
//    }

    /**
     * 删除评论
     */
//    @RequiresRoles("role_root")
//    @RequiresPermissions("user:delete")
//    @RequiresAuthentication
//    @RequestMapping("comment/delete/{id}")
//    public Result delete(@PathVariable(name = "id") String id) {
//
//        if (commentService.removeById(id)) {
//            return Result.succ(null);
//        } else {
//            return Result.fail("删除失败");
//        }
//
//    }

    /**
     * 提交评论
     */
    @AccessLimit(seconds = 30, maxCount = 1, msg = "30秒内只能提交一次评论")
    @VisitLogger(behavior = "提交评论")
    @PostMapping("/comment/add")
    public Result edit(@Validated @RequestBody Comment comment, HttpServletRequest request) throws Exception {

        if (comment.getContent().contains("<script>") || comment.getEmail().contains("<script>") || comment.getNickname().contains("<script>") || comment.getWebsite().contains("<script>")) {
            return Result.fail("非法输入");
        }
        System.out.println(comment.toString());
        Comment temp = new Comment();
        temp.setCreateTime(LocalDateTime.now());
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            // 前端通过搜狐API获取ip放到header里面
            ip = request.getHeader("yourIp");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        temp.setIp(ip);
        /*if (null == ip) {
            //如果Ip为空，不让进行操作
            throw new CiliciliException(CiliciliErrorCodeEnum.NOT_IP);
        }

        暂时不需要对文章评论条数 内容加以限制 可以自由发挥，后续如果有问题，用管理后台审核功能即可

        */
        BeanUtil.copyProperties(comment, temp, "id", "ip", "createTime");
        commentService.saveOrUpdate(temp);


        //博主的回复向被回复者发送提示邮件
        if (comment.getIsAdminComment() == 1 && comment.getParentCommentId() != -1) {
            Comment parentComment = commentService.getOne(new QueryWrapper<Comment>().eq("nickname", comment.getParentCommentNickname()));
            String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
            if (parentComment.getEmail().matches(regex)) {
                mailService.sendSimpleMail(parentComment.getEmail(), "Cheems博客评论回复", "您的的评论：" + parentComment.getContent() + "\n<br/> <br/> 博主回复内容：" + comment.getContent());
                logger.info("邮件发送成功");
            }

        }

        return Result.succ(null);
    }

    @GetMapping("/mail/send")
    public Result sendMailTest() throws Exception {

        mailService.sendSimpleMail("1771947201@qq.com", "Cheems博客评论回复", "您的的评论："  + "\n博主回复内容：+ comment.getContent()" );


        return Result.succ(null);

    }

}
